<template>
  <div class="query-form">
    <!-- 运行页面请求输入框 -->
    <el-form :model="form" :inline="true">
      <el-row :gutter="10">
        <el-col :span="isShowSaveInterfaceBtn ? (data.tag == '用例' ? 19 : 20) : 22">
          <el-input v-model="form.path" @change="changeUrl" v-if="isEnv">
            <template #prepend><span style="margin: 0 10px" :style="{ color: methodStyle[form.requestType] }">{{
              form.requestType
                }}</span>
              <el-tooltip class="box-item" effect="light" raw-content placement="top">
                <template #content>
                  <div>来自环境"{{ envName }}",<span @click="updateEnv" class="update">去修改</span></div>
                </template>
                <span class="service">{{ envUrl }}</span>
              </el-tooltip></template>
          </el-input>
          <el-input v-model="form.url" @change="changeUrl" v-else @keyup.enter="onSubmit">
            <template #prepend><span style="margin: 0 10px" :style="{ color: methodStyle[form.requestType] }">{{
              form.requestType
                }}</span></template>
          </el-input>
        </el-col>
        <el-col :span="isShowSaveInterfaceBtn ? (data.tag == '用例' ? 5 : 4) : 2">
          <el-button type="primary" :disabled="btnIsDisabled" @click="onSubmit">调试</el-button>
          <el-button @click="onSave" :disabled="btnIsDisabled" v-show="isShowSaveInterfaceBtn" type="primary" plain>{{
            data.tag
              == '用例' ? '保存' : '保存用例' }}</el-button>
          <el-button type="danger" plain @click="onDelete"
            v-show="isShowSaveInterfaceBtn && data.tag == '用例'">删除</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes'
import { splitUrl } from '@/utils/url'
import { useDebugStore } from '@/store/modules/debug'
import { getServiceURL } from '@/api/environment'
const message = useMessage() // 消息
const { t } = useI18n() // 国际化
const debugStore = useDebugStore()
const emit = defineEmits(['save-case', 'debug', 'formValue', 'save', 'to-delete', 'open-env', 'paramsValue'])
const props = defineProps({
  data: propTypes.object.def({})
})
const btnIsDisabled = ref(false)
let form = reactive({
  path: '',
  hostname: '',
  requestType: props.data.requestType,
  protocal: 'http',
  url: props.data.url,
  params: []
} as any)
const service = ref([] as any)
const envUrl = computed(() => service.value[0]?.conditionUrl?.trim() || '')
const isEnv = ref(false)
const environmentId = computed(() => debugStore.getEnvironmentId)
const environments = computed(() => debugStore.getEnvironments)
const envName = computed(() => {
  if (environmentId.value) {
    return environments.value.find((e) => e.id == environmentId.value).name || ''
  }
})
const methodStyle = ref({
  GET: '#17b26a',
  POST: '#ef6820',
  DELETE: '#f04438',
  PUT: '#2e90fa'
})
const isShowSaveInterfaceBtn = inject('isShowSaveInterfaceBtn')
watch(
  () => environmentId.value,
  async (newVal) => {
    isEnv.value = newVal ? true : false
    changeUrl()
  }
)
const updateEnv = () => {
  emit('open-env')
}
const onSubmit = () => {
  emit('debug')
}
/** save-case 从接口保存用例  save 用例本身保存 */
const onSave = () => {
  props.data.tag == '用例' ? emit('save') : emit('save-case')
}
/** 删除用例 */
const onDelete = async () => {
  emit('to-delete')
}
function getAllParameters(url) {
  var searchParams = new URLSearchParams(new URL('https://tiles.geovisearth.com' + url).search);
  var params = [];
  for (let p of searchParams.entries()) {
    params.push({
      keyName: p[0],
      keyValue: p[1],
      keyType: 'string',
      enable: false,
      keyDesc: ""
    })
    // params[p[0]] = p[1];
  }
  return params;
}
/** url变化处理，有无环境变量时url、path等做同步处理，并向上发送form */
const changeUrl = async () => {
  isEnv.value && (await getService())
  btnIsDisabled.value = false
  if (form.url.indexOf('=') != -1) {
    form.params = getAllParameters(form.url)
    emit('paramsValue', form)
  }
  // 选择了环境，但是没有配置服务地址
  if (!envUrl.value && isEnv.value) {
    message.warning('该环境服务地址为空，请前往进行配置！')
    btnIsDisabled.value = true
    return
  }
  // 向上传递的form
  const formValue = {
    url: isEnv.value ? `${envUrl.value}${form.path}` : form.url,
    requestType: form.requestType,
    protocal: form.protocal
  }
  // 有无环境时，对立情况要及时更新
  if (isEnv.value) {
    form.url = `${envUrl.value}${form.path}`
  } else {
    // const splitUrlList = splitUrl(form.url)
    // form.path = splitUrlList?.path
    // form.hostname = splitUrlList?.hostname
  }
  emit('formValue', { ...formValue, name: props.data.name })
}
/** 获取服务 */
const getService = async () => {
  if (!environmentId.value) return
  const res = await getServiceURL({ systemEnvId: environmentId.value })
  service.value = res || []
}
watch(
  () => props.data,
  () => {
    init()
  },
  {
    deep: true
  }
)
const init = async () => {
  await getService()
  // 选择环境但是没有服务，进行提示，并禁用功能按钮
  if (!envUrl.value && environmentId.value) {
    message.warning('该环境服务地址为空，请前往进行配置！')
    btnIsDisabled.value = true
  }
  // url地址拆分
  let splitUrlList = {} as any,
    url = ''
  // 只有路径
  if (props.data.url?.indexOf('http') == -1) {
    // 没有环境服务，禁用功能，显示路径
    if (!envUrl.value) {
      btnIsDisabled.value = true
      form.path = props.data.url
      form.url = props.data.url
      form.requestType = props.data.requestType
    } else {
      // 有环境服务
      url = `${envUrl.value}${props.data.url}`
      splitUrlList = splitUrl(url?.replace(/([^:]\/)\/+/g, '$1'))
    }
  } else {
    // 有完整地址，根据有无环境服务进行区别处理
    splitUrlList = splitUrl(props.data.url)
    if (envUrl.value) {
      url = envUrl.value + splitUrlList.path
    } else {
      url = props.data.url
    }
    splitUrlList = splitUrl(url)
  }
  if (splitUrlList?.path) {
    form = {
      url: props.data.url,
      requestType: props.data.requestType,
      path: splitUrlList?.path,
      hostname: splitUrlList?.hostname,
      protocal: splitUrlList?.protocol
    }
  }
  // 向上发送的form
  const formValue = {
    url: url?.replace(/([^:]\/)\/+/g, '$1'),
    requestType: props.data.requestType,
    protocal: form.protocal
  }
  environmentId.value && envUrl.value && (isEnv.value = true)
  emit('formValue', { ...formValue, name: props.data.name })
}
onMounted(async () => {
  init()
})
</script>

<style scoped lang="scss">
:deep(.el-input-group__prepend) {
  padding: 0;

  .service {
    padding: 0 10px;
  }

  .el-select {
    width: 120px;
    margin: 0;
  }
}

.update {
  cursor: pointer;

  &:hover {
    color: #409eff;
    text-decoration: underline;
  }
}
</style>
